(function() {
    // 默认设置
    let settings = {
        fontSize: '14',
        lineHeight: '1.5',
        fontColor: '#333333', // 默认字体颜色
        hotkeyNext: 'Ctrl+Shift+Right',
        hotkeyPrev: 'Ctrl+Shift+Left',
        windowLength: '60' // 显示字数
    };

    // 文件内容和阅读状态
    let fileContent = '';
    let fileName = '';
    let currentPosition = 0;
    let visible = false;
    let floatingWindow = null;
    let isDragging = false;
    let dragOffset = null; // 拖拽时的鼠标偏移量
    let lastPageChangeTime = Date.now(); // 记录上次翻页时间
    let pageCount = 0; // 总页数
    let hideTimer = null; // 隐藏计时器

    // 初始化函数
    function init() {
        // 从存储加载设置
    chrome.storage.sync.get([
        'fontSize', 'lineHeight', 'fontColor', 'hotkeyNext', 'hotkeyPrev', 'windowLength',
        'fileName', 'currentPosition'
    ], function(result) {
        // 应用保存的设置
        if (result.fontSize) settings.fontSize = result.fontSize;
        if (result.lineHeight) settings.lineHeight = result.lineHeight;
        if (result.fontColor) settings.fontColor = result.fontColor;
        if (result.hotkeyNext) settings.hotkeyNext = result.hotkeyNext;
        if (result.hotkeyPrev) settings.hotkeyPrev = result.hotkeyPrev;
        if (result.windowLength) settings.windowLength = result.windowLength;
        
        // 加载文件名和位置
        fileName = result.fileName || '未命名文件';
        currentPosition = result.currentPosition || 0;
        
        // 从local storage加载大文件内容
        if (chrome.storage && chrome.storage.local) {
            chrome.storage.local.get(['fileContent'], function(localResult) {
                if (localResult.fileContent) {
                    fileContent = localResult.fileContent;
                    showCurrentContent();
                }
            });
        }
    });

        // 创建浮窗元素
        createFloatingWindow();

        // 监听快捷键
        document.addEventListener('keydown', handleKeyDown);

        // 监听来自popup的消息
        chrome.runtime.onMessage.addListener(handleMessage);
    }

    // 创建浮窗元素
    function createFloatingWindow() {
        // 检查是否已经存在浮窗
        if (document.getElementById('stealth-reader-window')) {
            return;
        }

        if (floatingWindow) {
            floatingWindow.remove();
        }

        floatingWindow = document.createElement('div');
        floatingWindow.id = 'stealth-reader-window';
        floatingWindow.className = 'stealth-reader';
        floatingWindow.style.position = 'fixed'; // 固定定位
        floatingWindow.style.zIndex = '9999';
        
        // 固定在浏览器左下角，使用具体的像素值
        floatingWindow.style.left = '10px';
        floatingWindow.style.bottom = '10px';
        floatingWindow.style.top = 'auto'; // 确保top不会覆盖bottom设置
        floatingWindow.style.transform = 'none'; // 移除变换属性
        floatingWindow.style.fontSize = settings.fontSize + 'px';
        floatingWindow.style.lineHeight = settings.lineHeight;
        floatingWindow.style.opacity = '0.1'; // 默认隐藏状态的透明度
        floatingWindow.style.color = settings.fontColor;
        floatingWindow.style.backgroundColor = 'transparent'; // 透明背景
        floatingWindow.style.padding = '4px 8px'; // 减少内边距
        floatingWindow.style.border = 'none'; // 无边框
        floatingWindow.style.borderRadius = '0'; // 无圆角
        floatingWindow.style.boxShadow = 'none'; // 无阴影
        floatingWindow.style.maxWidth = '80%';
        floatingWindow.style.textAlign = 'center';
        floatingWindow.style.cursor = 'move';
        floatingWindow.style.transition = 'opacity 0.3s, background-color 0.3s';
        floatingWindow.style.display = 'none';
        floatingWindow.style.userSelect = 'none';
        floatingWindow.style.webkitUserSelect = 'none';
        floatingWindow.style.mozUserSelect = 'none';
        floatingWindow.style.msUserSelect = 'none';

        // 添加文件名和页码显示
        const fileNameElement = document.createElement('div');
        fileNameElement.className = 'stealth-reader-filename';
        fileNameElement.style.fontSize = (parseInt(settings.fontSize) - 2) + 'px';
        fileNameElement.style.color = '#666';
        fileNameElement.style.marginBottom = '5px';
        fileNameElement.style.display = 'none';
        
        // 添加页码显示
        const pageInfoElement = document.createElement('div');
        pageInfoElement.className = 'stealth-reader-pageinfo';
        pageInfoElement.style.fontSize = (parseInt(settings.fontSize) - 3) + 'px';
        pageInfoElement.style.color = '#999';
        pageInfoElement.style.marginTop = '3px';
        pageInfoElement.style.display = 'none';

        // 添加内容显示区域
        const contentElement = document.createElement('div');
        contentElement.className = 'stealth-reader-content';
        contentElement.style.overflow = 'hidden';
        contentElement.style.whiteSpace = 'nowrap';
        contentElement.style.textOverflow = 'ellipsis';
        contentElement.style.color = settings.fontColor;

        floatingWindow.appendChild(fileNameElement);
        floatingWindow.appendChild(contentElement);
        floatingWindow.appendChild(pageInfoElement);
        
        // 安全地添加到页面
        if (document.body) {
            document.body.appendChild(floatingWindow);
        }

        // 添加拖拽功能
        floatingWindow.addEventListener('mousedown', startDrag);
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', stopDrag);

        // 添加双击隐藏/显示文件名
        floatingWindow.addEventListener('dblclick', function() {
            fileNameElement.style.display = fileNameElement.style.display === 'none' ? 'block' : 'none';
        });

        // 添加悬停效果（增强隐蔽性）
        floatingWindow.addEventListener('mouseenter', function() {
            // 清除隐藏计时器
            if (hideTimer) {
                clearTimeout(hideTimer);
                hideTimer = null;
            }
            floatingWindow.style.opacity = '1';
            // 保持透明背景，不改变
        });

        floatingWindow.addEventListener('mouseleave', function() {
            // 设置延迟隐藏
            if (hideTimer) {
                clearTimeout(hideTimer);
            }
            hideTimer = setTimeout(function() {
                // 检查是否在这段时间内没有翻页
                const now = Date.now();
                if (now - lastPageChangeTime > 3000) { // 3秒
                    floatingWindow.style.opacity = '0.1'; // 隐藏时透明度为0.1
                    floatingWindow.style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
                }
                hideTimer = null;
            }, 3000); // 3秒后执行
        });
    }

    // 拖拽功能实现
    function startDrag(e) {
        isDragging = true;
        
        // 获取浮窗的实际位置，不依赖于CSS样式属性
        const rect = floatingWindow.getBoundingClientRect();
        
        // 记录鼠标位置和浮窗的相对位置
        const offsetX = e.clientX - rect.left;
        const offsetY = e.clientY - rect.top;
        
        // 保存偏移量用于计算拖拽位置
        dragOffset = { x: offsetX, y: offsetY };
        
        // 移除transform属性，使用直接定位
        floatingWindow.style.transform = 'none';
        floatingWindow.style.left = rect.left + 'px';
        floatingWindow.style.top = rect.top + 'px';
        
        floatingWindow.style.zIndex = '10000';
    }

    function drag(e) {
        if (!isDragging || !dragOffset) return;

        // 使用鼠标位置减去偏移量来计算浮窗的新位置
        const newLeft = e.clientX - dragOffset.x;
        const newTop = e.clientY - dragOffset.y;
        
        // 应用新位置
        floatingWindow.style.left = newLeft + 'px';
        floatingWindow.style.top = newTop + 'px';
    }

    function stopDrag() {
        isDragging = false;
        dragOffset = null;
        floatingWindow.style.zIndex = '9999';
    }

    // 计算总页数
    function calculatePageCount() {
        if (!fileContent) {
            pageCount = 0;
            return;
        }
        
        const displayWordCount = parseInt(settings.windowLength);
        pageCount = Math.ceil(fileContent.length / displayWordCount);
    }
    
    // 获取当前页码
    function getCurrentPage() {
        if (pageCount === 0) return 0;
        
        const displayWordCount = parseInt(settings.windowLength);
        return Math.floor(currentPosition / displayWordCount) + 1;
    }
    
    // 显示页码信息
    function updatePageInfo() {
        if (!floatingWindow) return;
        
        let pageInfoElement = floatingWindow.querySelector('.stealth-reader-pageinfo');
        if (!pageInfoElement) {
            pageInfoElement = document.createElement('div');
            pageInfoElement.className = 'stealth-reader-pageinfo';
            pageInfoElement.style.fontSize = (parseInt(settings.fontSize) - 3) + 'px';
            pageInfoElement.style.color = '#999';
            pageInfoElement.style.marginTop = '3px';
            pageInfoElement.style.display = 'none';
            floatingWindow.appendChild(pageInfoElement);
        }
        
        calculatePageCount();
        const currentPage = getCurrentPage();
        
        if (pageInfoElement) {
            pageInfoElement.textContent = `${currentPage}/${pageCount}`;
        }
    }
    
    // 跳转到指定页码
    function goToPage(pageNumber) {
        if (pageCount === 0 || pageNumber < 1 || pageNumber > pageCount) return;
        
        // 获取当前设置的显示字数（确保跳转时字数不变）
        const displayWordCount = parseInt(settings.windowLength);
        
        // 严格按照显示字数计算跳转位置
        currentPosition = (pageNumber - 1) * displayWordCount;
        
        // 保存当前位置
        if (chrome.storage && chrome.storage.sync) {
            chrome.storage.sync.set({ currentPosition: currentPosition }, function() {
                if (chrome.runtime.lastError) {
                    // 静默处理错误
                }
            });
        }
        
        // 更新上次翻页时间
        lastPageChangeTime = Date.now();
        
        // 显示内容
        showCurrentContent();
    }

    // 显示当前内容
    function showCurrentContent() {
        if (!floatingWindow || !fileContent) return;

        // 确保创建了必要的元素
        let contentElement = floatingWindow.querySelector('.stealth-reader-content');
        let fileNameElement = floatingWindow.querySelector('.stealth-reader-filename');
        let pageInfoElement = floatingWindow.querySelector('.stealth-reader-pageinfo');
        
        // 如果元素不存在，重新创建
        if (!contentElement) {
            contentElement = document.createElement('div');
            contentElement.className = 'stealth-reader-content';
            contentElement.style.overflow = 'hidden';
            contentElement.style.whiteSpace = 'nowrap';
            // 移除textOverflow: 'ellipsis'，避免显示省略号
            floatingWindow.appendChild(contentElement);
        }
        
        if (!fileNameElement) {
            fileNameElement = document.createElement('div');
            fileNameElement.className = 'stealth-reader-filename';
            fileNameElement.style.fontSize = (parseInt(settings.fontSize) - 2) + 'px';
            fileNameElement.style.color = '#666';
            fileNameElement.style.marginBottom = '5px';
            fileNameElement.style.display = 'none';
            floatingWindow.appendChild(fileNameElement);
        }
        
        if (!pageInfoElement) {
            pageInfoElement = document.createElement('div');
            pageInfoElement.className = 'stealth-reader-pageinfo';
            pageInfoElement.style.fontSize = (parseInt(settings.fontSize) - 3) + 'px';
            pageInfoElement.style.color = '#999';
            pageInfoElement.style.marginTop = '3px';
            pageInfoElement.style.display = 'none';
            floatingWindow.appendChild(pageInfoElement);
        }
        
        if (fileNameElement) {
            fileNameElement.textContent = fileName;
        }

        if (contentElement) {
            // 使用设置中的显示字数
            const displayWordCount = parseInt(settings.windowLength);
            // 确保内容元素颜色与设置一致
            contentElement.style.color = settings.fontColor;
            
            // 从当前位置获取固定长度的内容（严格按字数计算）
            let currentLine = '';
            if (currentPosition < fileContent.length) {
                const endPos = Math.min(currentPosition + displayWordCount, fileContent.length);
                currentLine = fileContent.substring(currentPosition, endPos).trim();
                
                // 处理内容末尾（仅影响显示，不影响翻页计算）
                if (endPos < fileContent.length) {
                    // 找到最近的空格，避免在单词中间截断显示
                    const lastSpace = currentLine.lastIndexOf(' ');
                    if (lastSpace > displayWordCount * 0.7) { // 确保保留大部分内容
                        currentLine = currentLine.substring(0, lastSpace);
                    }
                }
            }
            
            contentElement.textContent = currentLine || '已到达文件末尾';
        }
        
        // 更新页码信息
        updatePageInfo();

        // 确保窗口可见
        if (!visible && fileContent) {
            floatingWindow.style.display = 'block';
            visible = true;
        }
    }

    // 下一页
    function nextPage() {
        if (!fileContent || !floatingWindow) return;

        // 获取当前设置的显示字数（确保翻页时字数不变）
        const displayWordCount = parseInt(settings.windowLength);
        
        // 严格按照显示字数计算下一页的位置
        const nextPosition = currentPosition + displayWordCount;
        
        if (nextPosition < fileContent.length) {
            currentPosition = nextPosition;
            
            // 更新上次翻页时间
            lastPageChangeTime = Date.now();
            
            // 保存当前位置
            if (chrome.storage && chrome.storage.sync) {
                chrome.storage.sync.set({ currentPosition: currentPosition }, function() {
                    if (chrome.runtime.lastError) {
                        // 静默处理错误
                    }
                });
            }
            
            // 显示下一页内容
            showCurrentContent();
        }
    }

    // 上一页
    function prevPage() {
        if (!fileContent || currentPosition <= 0 || !floatingWindow) return;

        // 获取当前设置的显示字数（确保翻页时字数不变）
        const displayWordCount = parseInt(settings.windowLength);
        
        // 严格按照显示字数计算上一页的位置
        currentPosition = Math.max(0, currentPosition - displayWordCount);
        
        // 更新上次翻页时间
        lastPageChangeTime = Date.now();
        
        // 保存当前位置
        if (chrome.storage && chrome.storage.sync) {
            chrome.storage.sync.set({ currentPosition: currentPosition }, function() {
                if (chrome.runtime.lastError) {
                    // 静默处理错误
                }
            });
        }
        
        // 显示上一页内容
        showCurrentContent();
    }

    // 处理键盘事件
    function handleKeyDown(e) {
        // 只有在文件内容存在且窗口可见时才处理快捷键
        if (!fileContent || !visible) return;
        
        // 检查修饰键状态
        const hasCtrl = e.ctrlKey || e.metaKey; // metaKey 是 Mac 上的 Command 键
        const hasShift = e.shiftKey;
        const hasAlt = e.altKey;
        
        // 获取当前快捷键设置
        const nextKey = settings.hotkeyNext || 'Right';
        const prevKey = settings.hotkeyPrev || 'Left';
        
        // 支持带修饰键的快捷键组合
        // 格式如: Ctrl+Shift+Right 或 Right
        const checkHotkey = (keySetting, eventKey) => {
            if (!keySetting) return false;
            
            // 检查是否为简单按键
            if (keySetting === eventKey) return true;
            
            // 检查是否为组合键
            const parts = keySetting.split('+').map(part => part.trim());
            
            // 检查修饰键
            let hasRequiredCtrl = parts.includes('Ctrl') || parts.includes('Command');
            let hasRequiredShift = parts.includes('Shift');
            let hasRequiredAlt = parts.includes('Alt');
            
            // 检查主按键
            let mainKey = parts.find(part => !['Ctrl', 'Command', 'Shift', 'Alt'].includes(part));
            
            // 只有当所有修饰键都匹配且主按键匹配时才返回true
            return (!hasRequiredCtrl || hasCtrl) && 
                   (!hasRequiredShift || hasShift) && 
                   (!hasRequiredAlt || hasAlt) && 
                   mainKey && (mainKey === eventKey || mainKey === 'Arrow' + eventKey);
        };
        
        // 检查下一页快捷键
        if (checkHotkey(nextKey, e.key) || e.key === 'ArrowRight') {
            nextPage();
            e.preventDefault();
        } 
        // 检查上一页快捷键
        else if (checkHotkey(prevKey, e.key) || e.key === 'ArrowLeft') {
            prevPage();
            e.preventDefault();
        }
    }

    // 处理来自popup的消息
    function handleMessage(message, sender, sendResponse) {
        try {
            // 确保sendResponse是一个函数
            const safeSendResponse = typeof sendResponse === 'function' ? sendResponse : function() {};
            
            if (message.action === 'updateContent') {
                fileContent = message.content;
                fileName = message.fileName || '未命名文件';
                currentPosition = message.position || 0;
                
                // 将大文件内容保存到local storage，其他信息保存到sync storage
                if (chrome.storage) {
                    // 保存到local storage (更大的配额)
                    if (chrome.storage.local) {
                        chrome.storage.local.set({ fileContent: fileContent }, function() {
                            if (chrome.runtime.lastError) {
                                console.log('保存文件内容失败：' + chrome.runtime.lastError.message);
                            }
                        });
                    }
                    
                    // 保存其他信息到sync storage
                    if (chrome.storage.sync) {
                        chrome.storage.sync.set({
                            fileName: fileName,
                            currentPosition: currentPosition
                        }, function() {
                            if (chrome.runtime.lastError) {
                                console.log('保存文件信息失败：' + chrome.runtime.lastError.message);
                            }
                        });
                    }
                }
                
                // 显示内容
                showCurrentContent();
                
                safeSendResponse({ status: 'success' });
                return true; // 表示异步响应
            } else if (message.action === 'updateSettings') {
                // 更新设置
                if (message.settings.fontSize) settings.fontSize = message.settings.fontSize;
                if (message.settings.lineHeight) settings.lineHeight = message.settings.lineHeight;
                if (message.settings.fontColor) settings.fontColor = message.settings.fontColor;
                if (message.settings.hotkeyNext) settings.hotkeyNext = message.settings.hotkeyNext;
                if (message.settings.hotkeyPrev) settings.hotkeyPrev = message.settings.hotkeyPrev;
                if (message.settings.windowLength) settings.windowLength = message.settings.windowLength;
                
                // 应用设置到浮窗
                if (floatingWindow) {
                    floatingWindow.style.fontSize = settings.fontSize + 'px';
                    floatingWindow.style.lineHeight = settings.lineHeight;
                    floatingWindow.style.color = settings.fontColor;
                    
                    // 确保内容元素颜色也更新
                    const contentElement = floatingWindow.querySelector('.stealth-reader-content');
                    if (contentElement) {
                        contentElement.style.color = settings.fontColor;
                    }
                    
                    const fileNameElement = floatingWindow.querySelector('.stealth-reader-filename');
                    const pageInfoElement = floatingWindow.querySelector('.stealth-reader-pageinfo');
                    
                    if (fileNameElement) {
                        fileNameElement.style.fontSize = (parseInt(settings.fontSize) - 2) + 'px';
                    }
                    
                    if (pageInfoElement) {
                        pageInfoElement.style.fontSize = (parseInt(settings.fontSize) - 3) + 'px';
                    }
                    
                    // 重新显示内容以适应新的设置
                    showCurrentContent();
                }
                
                safeSendResponse({ status: 'success' });
                return true; // 表示异步响应
            } else if (message.action === 'syncContent') {
                // 同步内容（当切换标签页时）
                fileName = message.fileName || '未命名文件';
                currentPosition = message.position || 0;
                
                // 如果没有提供内容，尝试从local storage加载
                if (message.content) {
                    fileContent = message.content;
                    showCurrentContent();
                } else if (chrome.storage && chrome.storage.local) {
                    chrome.storage.local.get(['fileContent'], function(localResult) {
                        if (localResult.fileContent) {
                            fileContent = localResult.fileContent;
                            showCurrentContent();
                        }
                    });
                }
                
                safeSendResponse({ status: 'success' });
                return true; // 表示异步响应
            } else if (message.action === 'nextPage') {
                // 处理下一页命令
                nextPage();
                safeSendResponse({ status: 'success' });
                return true;
            } else if (message.action === 'prevPage') {
                // 处理上一页命令
                prevPage();
                safeSendResponse({ status: 'success' });
                return true;
            } else if (message.action === 'goToPage') {
                // 处理跳页命令
                const pageNumber = parseInt(message.pageNumber);
                if (!isNaN(pageNumber)) {
                    goToPage(pageNumber);
                    safeSendResponse({ status: 'success' });
                } else {
                    safeSendResponse({ status: 'error', message: '无效的页码' });
                }
                return true;
            } else {
                // 未知消息类型
                safeSendResponse({ status: 'error', message: '未知消息类型' });
                return true;
            }
        } catch (error) {
            console.error('处理消息时出错:', error);
            if (typeof sendResponse === 'function') {
                sendResponse({ status: 'error', message: error.message });
            }
            return true;
        }
    }

    // 添加自定义CSS样式
    function addCustomStyles() {
        const style = document.createElement('style');
        style.textContent = `
            #stealth-reader-window {
                pointer-events: auto !important;
            }
            #stealth-reader-window.stealth-reader {
                -webkit-filter: blur(0px);
                filter: blur(0px);
                transition: opacity 0.3s ease;
            }
            #stealth-reader-window:hover {
                box-shadow: none !important;
                background-color: transparent !important;
            }
            /* 防止页面滚动时影响浮窗 */
            html {
                scroll-behavior: auto !important;
            }
        `;
        document.head.appendChild(style);
    }

    // 添加安全模式（当检测到活动窗口切换时自动降低可见性）
    function setupSafeMode() {
        let lastActiveTime = Date.now();
        let isAway = false;
        
        // 监听鼠标移动和键盘事件
        document.addEventListener('mousemove', function() {
            lastActiveTime = Date.now();
            if (isAway && floatingWindow) {
                floatingWindow.style.opacity = settings.opacity;
                isAway = false;
            }
        });
        
        document.addEventListener('keydown', function() {
            lastActiveTime = Date.now();
            if (isAway && floatingWindow) {
                floatingWindow.style.opacity = settings.opacity;
                isAway = false;
            }
        });
        
        // 定期检查用户活动
        setInterval(function() {
            if (visible && floatingWindow && Date.now() - lastActiveTime > 5000) { // 5秒无活动
                floatingWindow.style.opacity = '0.3';
                isAway = true;
            }
        }, 1000);
    }

    // 启动插件
    function startPlugin() {
        addCustomStyles();
        init();
        setupSafeMode();
    }
    
    // 确保DOM已完全加载
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startPlugin);
    } else {
        startPlugin();
    }
})();